package com.example.transaction.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.transaction.common.vo.Result;
import com.example.transaction.sys.entity.*;
import com.example.transaction.sys.service.IItemService;
import com.example.transaction.sys.service.IOrderService;
import com.example.transaction.sys.service.IUserService;
//import com.sun.org.apache.xpath.internal.operations.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zh
 * @since 2023-06-20
 */
@RestController
@RequestMapping("/sys/order")
public class OrderController {

    @Autowired
    private IOrderService orderService;
    @Autowired
    private  IItemService itemService;
    @Autowired
    private IUserService userService;

    @Cacheable(value = "orders", key = "'allorders'")
    @GetMapping("/all")
    public Result<List<Order>> getAllOrder(){
        List<Order>list=orderService.list();
        return Result.success(list,"查询成功");
    }

    /**
     * 新增订单接口
     * @param
     * @return
     */
    @CacheEvict(value = "orders", allEntries = true)
    @PostMapping("/addOrder")
    public Result<?>addOrder(@RequestParam(value = "itemID")Integer itemID,
                             @RequestParam(value = "buyerID")Integer buyerID,
                             @RequestParam(value = "sellerID")Integer sellerID,
                             @RequestParam(value = "orderStatus")String orderStatus,
                             @RequestParam(value = "addressID")Integer addressID){
        Order order = new Order();
        order.setItemID(itemID);
        order.setBuyerID(buyerID);
        order.setSellerID(sellerID);
        order.setOrderStatus(orderStatus);
        order.setAddressID(addressID);

        LocalDateTime createTime = LocalDateTime.now();
        order.setCreationTime(createTime);

        LocalDateTime expireTime = createTime.plusMinutes(30);
        order.setExpireTime(expireTime);
        try {
            orderService.save(order);
        }catch (Exception e){
            return Result.fail("新增失败");
        }
        return Result.success(order.getOrderID(),"新增订单成功");
    }

    /**
     * 删除订单
     * @param id
     * @return
     */
    @CacheEvict(value = "orders", allEntries = true)
    @DeleteMapping("/{id}")
    public Result<User>deleteUserById(@PathVariable("id")Integer id){
        orderService.removeById(id);
        return Result.success("删除订单成功");
    }

    /**
     * 根据订单id查找信息
     * @param id
     * @return
     */
    @Cacheable(value = "orders", key = "#id")
    @GetMapping("/getinfo/{id}")
    public Result<Order>getUserById(@PathVariable("id")Integer id){
        Order order=orderService.getById(id);
        return Result.success(order);
    }

    /**
     * 查询所有订单，或者按条件查询
     * @param
     * @param
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Cacheable(value = "orders", key = "'allorders'+#itemName+#buyerName+#sellerName+#orderStatus+#pageNo+#pageSize")
    @GetMapping("/list")
    public Result<Map<String,Object>>getUserList(@RequestParam(value = "itemName",required = false)String itemName,
                                                 @RequestParam(value = "buyerName",required = false)String buyerName,
                                                 @RequestParam(value = "sellerName",required = false)String sellerName,
                                                 @RequestParam(value = "orderStatus",required = false)String orderStatus,
                                                 @RequestParam(value = "pageNo")Long pageNo,
                                                 @RequestParam(value = "pageSize")Long pageSize){
        LambdaQueryWrapper<Order> wrapper=new LambdaQueryWrapper<>();
//        wrapper.eq(StringUtils.hasLength(itemID),Order::getItemID,itemID);     //模糊查询
//        wrapper.eq(StringUtils.hasLength(buyerID),Order::getBuyerID,buyerID);
//        wrapper.eq(StringUtils.hasLength(sellerID),Order::getSellerID,sellerID);
        wrapper.eq(StringUtils.hasLength(orderStatus),Order::getOrderStatus,orderStatus);
        if (StringUtils.hasLength(itemName)) {
            List<Integer> itemIds = itemService.getItemIdsByItemNameLike(itemName);
            if (!itemIds.isEmpty()) {
                wrapper.in(Order::getItemID, itemIds);
            }else{
                List<Map<String, Object>> rows = new ArrayList<>();
                Map<String, Object> data = new HashMap<>();
                data.put("total", 0);
                data.put("rows", rows);
                return Result.success(data);
            }
        }

        if (StringUtils.hasLength(buyerName)) {
            List<Integer> buyerIds = userService.getUserIdsByUsernameLike(buyerName);
            if (!buyerIds.isEmpty()) {
                wrapper.in(Order::getBuyerID, buyerIds);
            }
            else{
                List<Map<String, Object>> rows = new ArrayList<>();
                Map<String, Object> data = new HashMap<>();
                data.put("total", 0);
                data.put("rows", rows);
                return Result.success(data);
            }
        }

        if (StringUtils.hasLength(sellerName)) {
            List<Integer> sellerIds = userService.getUserIdsByUsernameLike(sellerName);
            if (!sellerIds.isEmpty()) {
                wrapper.in(Order::getSellerID, sellerIds);
            }
            else{
                List<Map<String, Object>> rows = new ArrayList<>();
                Map<String, Object> data = new HashMap<>();
                data.put("total", 0);
                data.put("rows", rows);
                return Result.success(data);
            }
        }
        // 按 creationTime 倒序排序
        wrapper.orderByDesc(Order::getCreationTime);

        Page<Order> page=new Page<>(pageNo,pageSize);
        orderService.page(page,wrapper);

        List<Order> orderList = page.getRecords();
        List<Map<String, Object>> rows = new ArrayList<>();

        for (Order order : orderList) {
            Map<String, Object> row = new HashMap<>();
            row.put("orderID", order.getOrderID());
            row.put("itemID", order.getItemID());
            row.put("buyerID", order.getBuyerID());
            row.put("sellerID", order.getSellerID());
            row.put("creationTime", order.getCreationTime());
            row.put("orderStatus", order.getOrderStatus());
            row.put("itemName", itemService.getById(order.getItemID()).getItemName());
            row.put("buyerName", userService.getById(order.getBuyerID()).getUsername());
            row.put("sellerName", userService.getById(order.getSellerID()).getUsername());
            row.put("price", itemService.getById(order.getItemID()).getPrice());
            row.put("picture", itemService.getById(order.getItemID()).getItemImage());
            rows.add(row);
        }

        Map<String, Object> data = new HashMap<>();
        data.put("total", page.getTotal());
        data.put("rows", rows);
        return Result.success(data);
    }


    @Cacheable(value = "orders", key = "#datetime")
    @GetMapping("/{datetime}")
    public Result<List<Integer>> getItemIdsByOrderStatus(@PathVariable("datetime") LocalDate datetime) {
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getOrderStatus, "已完成");
        wrapper.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = {0}", datetime.toString());

        List<Order> orderList = orderService.list(wrapper);
        List<Integer> itemIds = new ArrayList<>();

        for (Order order : orderList) {
            itemIds.add(order.getItemID());
        }

        if (!itemIds.isEmpty()) {
            return Result.success(itemIds, "查询成功");
        } else {
            return Result.fail("没有找到符合条件的ItemID");
        }
    }

    /**  前段没有调用
     * 通过orderID查找price和image
     * @param orderId
     * @return
     */
    @GetMapping("/item")
    public Map<String, Object> getItemDetailsByOrderId(@RequestParam("orderID") Integer orderId) {
        Map<String, Object> itemDetails = new HashMap<>();

        // 根据订单ID查询订单
        Order order = orderService.getById(orderId);
        if (order != null) {
            Integer itemId = order.getItemID();
            Item item = itemService.getById(itemId);
            if (item != null) {
                Double price = item.getPrice();
                String imageName = item.getItemImage();

                itemDetails.put("price", price);
                itemDetails.put("imageName", imageName);
            }
        }

        return itemDetails;
    }

    /**
     * 根据订单id更新订单状态
     * @param id
     * @param status
     * @return
     */
    @CacheEvict(value = "orders", allEntries = true)
    @PutMapping("/status/{id}")
    public Result<Order> updateItemStatus(@PathVariable("id") Integer id,
                                         @RequestParam("status") String status,
                                          @RequestParam(value = "alipayTradeNo",required = false) String alipayTradeNo,
                                          @RequestParam(value = "date",required = false) Date date) {
        Order order = new Order();
        order.setOrderID(id);
        order.setOrderStatus(status);
        order.setAlipayNo(alipayTradeNo);
        order.setPayTime(date);
        orderService.updateById(order);
        return Result.success("更新订单状态成功");
    }

    /**
     * 管理员发货接口
     * @param id
     * @return
     */
    @CacheEvict(value = "orders", allEntries = true)
    @PutMapping("/send/{id}")
    public Result<Order> updateItemStatus(@PathVariable("id") Integer id) {
        Order order = new Order();
        order.setOrderID(id);
        order.setOrderStatus("待确认收货");
        orderService.updateById(order);
        return Result.success("更新订单状态成功");
    }

}
